import { reqProductList, reqGetMark, reqUpdateMark, reqDeleteMark, reqImageBatchUpdate, reqImageBatchDel } from "@api/api.js";
import asc from "@utils/asc.js"; //加密解密

export default {
    data() {
        return {
            dialogVisible: false,
            headers: {
                token: asc.decrypt(sessionStorage.getItem("token")),
            },
            productList: [],
            productId: "",
            isMark: '',
            isMarkList: [{
                id: '2',
                name: '已标记'
            }, {
                id: '3',
                name: '未标记'
            }, ],
            markId: '',
            markList: [],
            markVOList: [],
            left: 0,
            top: 0,
            flag: false,
            classIcon: "",

            // 放大缩小
            scale: 1, // 初始缩放比例为1
            scaleStep: 0.1, // 每次滚动缩放的步长

            // 鼠标拖动
            x: 0, // div的初始x坐标
            y: 0, // div的初始y坐标
            dragging: false, // 是否正在拖动
            startX: 0, // 鼠标按下时的x坐标
            startY: 0, // 鼠标按下时的y坐标

            dragging2: false, // 是否正在拖动
            startX2: 0, // 鼠标按下时的x坐标
            startY2: 0, // 鼠标按下时的y坐标

            itemInfo: {},
            image: "",
            baseUrl: "",
            shebei: require("@assets/images/shebei.png"),
            total: 0,

            dragging4: false, // 是否正在拖动
            startX4: 0, // 鼠标按下时的x坐标
            startY4: 0, // 鼠标按下时的y坐标

            divBoxWidth: 800,
            divBoxHeight: 450,
            page: 1,
            limit: 10,
        };
    },
    components: {},
    mounted() {},
    async created() {
        this.baseUrl = `${this.$baseURL_copy}file/upload`;
    },
    methods: {
        onDeleteMark() {
            this.$confirm("确认清空图上资源？", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(async() => {
                    const res = await reqDeleteMark(this.floorInfo.id)
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.getGetMark() //设备刷新
                })
                .catch(() => {});
        },
        // 删除单个设备
        async onDel() {
            this.$notify.closeAll();
            if (this.markId == '') return this.$modal.notifyWarning('请选择要删除的设备');
            this.$confirm("确认删除选中资源?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(async() => {
                    const res = await reqUpdateMark({
                        id: this.markId,
                        mark: ''
                    })
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.markId = ''
                    this.getGetMark() //未标记的设备刷新
                })
                .catch(() => {});
        },
        onDelplan() {
            this.$confirm("删除图片会删除平面图和图上资源，是否删除?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(async() => {
                    const res = await reqImageBatchDel({
                        idList: [this.floorInfo.id]
                    });
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.$modal.notifySuccess("删除成功");
                    this.floorInfo.image = '';
                    this.markId = ''
                    this.getGetMark() //未标记的设备刷新
                })
                .catch(() => {});
        },
        onEdit() {
            this.$confirm("确认更换平面图?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                .then(async() => {
                    // 手动触发文件选择对话框
                    this.$refs.upload.$el.querySelector('.el-upload__input').click();
                })
                .catch(() => {});
        },
        // 鼠标拖动
        // 用户按下鼠标按钮时触发
        handleMouseDown(event) {
            this.dragging = true;
            this.startX = event.clientX - this.x;
            this.startY = event.clientY - this.y;
        },
        // 用户移动鼠标时触发
        handleMouseMove(event) {
            if (!this.dragging) return;
            this.x = event.clientX - this.startX;
            this.y = event.clientY - this.startY;
        },
        // 用户释放鼠标按钮时触发
        handleMouseUp() {
            this.dragging = false;
        },
        handleMouseDown2(event, item, index) {
            this.markId = item.id
            this.dragging2 = true;
            this.dragging3 = false; //点击一下则不调用接口
            this.currentIndex = index; // 记录当前拖拽的点位索引
            // 拖拽时考虑当前的缩放比例，并将鼠标的坐标转换为缩放后的坐标。
            this.startX2 = (event.clientX - this.x - this.markVOList[index].left * this.scale) / this.scale;
            this.startY2 = (event.clientY - this.y - this.markVOList[index].top * this.scale) / this.scale;
            // 将 mousemove 和 mouseup 事件绑定到 document 可解决鼠标移动太快导致拖拽断掉的问题
            document.addEventListener('mousemove', this.handleMouseMove2);
            document.addEventListener('mouseup', this.handleMouseUp2);
        },

        handleMouseMove2(event) {
            if (!this.dragging2) return;

            const newLeft = (event.clientX - this.x - this.startX2 * this.scale) / this.scale;
            const newTop = (event.clientY - this.y - this.startY2 * this.scale) / this.scale;

            // 边界检查
            let adjustedLeft = newLeft;
            let adjustedTop = newTop;

            // 确保点位的左上角不会超出容器的左上边界
            if (adjustedLeft < 0) adjustedLeft = 0;
            if (adjustedTop < 0) adjustedTop = 0;

            // 确保点位的右下角不会超出容器的右下边界
            const containerWidth = this.divBoxWidth; // 容器宽度
            const containerHeight = this.divBoxHeight; // 容器高度
            const markWidth = 34; // 点位宽度
            const markHeight = 34; // 点位高度
            if (adjustedLeft + markWidth > containerWidth) adjustedLeft = containerWidth - markWidth;
            if (adjustedTop + markHeight > containerHeight) adjustedTop = containerHeight - markHeight;

            this.left = Math.round(adjustedLeft);
            this.top = Math.round(adjustedTop);
            this.dragging3 = true;

            const updatedItem = {
                ...this.markVOList[this.currentIndex],
                left: adjustedLeft,
                top: adjustedTop
            };
            this.$set(this.markVOList, this.currentIndex, updatedItem);
        },

        handleMouseUp2() {
            this.dragging2 = false;
            // 移除 document 上的事件监听
            document.removeEventListener('mousemove', this.handleMouseMove2);
            document.removeEventListener('mouseup', this.handleMouseUp2);
            // 是否移动过
            if (this.dragging3) {
                this.submit() // 修改标记
            }
        },
        onDragStart(item, index, event) {
            this.markId = item.id
        },
        onDrop(event) {
            console.log(this.markId, 'event');
            if (this.markId == '') return
            const floorImage = this.$refs.floorImage;
            const rect = floorImage.getBoundingClientRect();
            // 计算相对于平面图左上角的鼠标位置
            let relativeX = (event.clientX - rect.left) / this.scale - 15; //-15在鼠标中心位置
            let relativeY = (event.clientY - rect.top) / this.scale - 15;
            // 四舍五入到最近的整数，因为像素是离散的
            relativeX = Math.round(relativeX);
            relativeY = Math.round(relativeY);
            // 未标记
            this.left = relativeX;
            this.top = relativeY;
            this.submit() // 修改标记
        },
        onrecover() {
            this.scale = 1
            this.x = 0 // div的初始x坐标
            this.y = 0
        },
        onlargen() {
            this.scale += 0.3; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        onlessen() {
            this.scale -= 0.3; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        // 放大缩小
        handleWheel(event) {
            event.preventDefault(); // 阻止默认事件，防止页面滚动
            const delta = event.deltaY * -1; // 获取滚轮滚动的方向
            this.scale += delta > 0 ? this.scaleStep : -this.scaleStep; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        // 切换设备
        // async clickTree(item) {
        //     // console.log(this.markId,item);
        //     if (this.floorInfo.image == '') return
        //     if (this.markId == item.id) {
        //         // 点击相同设备
        //         this.markId = ''
        //         this.itemInfo = ''
        //         this.flag = false;
        //         return
        //     }
        //     this.itemInfo = item
        //         // 是否未标记
        //     if (item.mark == '') {
        //         this.flag = false;
        //     } else {
        //         this.flag = true;
        //     }
        //     this.markId = item.id
        // },
        // 切换设备
        async clickTree(item) {
            if (this.floorInfo.image == '') return
            this.markId = item.id
                // if (item.mark == '') {
                //     // 未标记
                //     this.left = 380;
                //     this.top = 200;
                //     this.submit(true) // 修改标记
                // }
        },
        //点击绘制标记
        setPoint(e) {
            //     if (this.markId == '') return
            //     e = e || window.event;
            //     if (this.flag) {
            //         // 已标记
            //         // 实时更新其属性： 创建一个新的对象来替换旧的数组元素。这样 Vue 可以检测到数组的变化：
            //         const newMarkVOList = this.markVOList.map(item => {
            //             if (item.id == this.markId) {
            //                 return {
            //                     ...item,
            //                     left: e.offsetX - 10 || e.layerX - 10,
            //                     top: e.offsetY - 17 || e.layerY - 17
            //                 };
            //             }
            //             return item;
            //         });
            //         this.markVOList = newMarkVOList;
            //     } else {
            //         // 未标记
            //         this.itemInfo.left = e.offsetX - 10 || e.layerX - 10;
            //         this.itemInfo.top = e.offsetY - 17 || e.layerY - 17;
            //         this.markVOList.push(this.itemInfo)
            //     }
            //     this.flag = true; //未标记变成已标记
            //     this.left = e.offsetX - 10 || e.layerX - 10;
            //     this.top = e.offsetY - 17 || e.layerY - 17;
            //     this.submit() // 修改标记
        },
        // 修改标记
        async submit(flag = false) {
            const res = await reqUpdateMark({
                id: this.markId,
                mark: this.left + "," + this.top
            })
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$notify.closeAll();
            if (flag) {
                this.$modal.notifySuccess("标记成功，请拖动图标到指定点位");
            } else {
                this.$modal.notifySuccess("修改标记成功");
            }
            this.getGetMark(true) //未标记的设备刷新
        },
        // 标记点图片
        // iconclass(e) {
        //     console.log(e);
        //     let pic = this.shebei
        //         this.productList.forEach(item => {
        //             if (item.name == e.productName) {
        //                 pic = item.pic
        //             }
        //         })
        //     return pic
        // },
        // 标记点图片
        iconclass(e) {
            // console.log(e);
            let pic = 'iconfont shebeiguanli2'
            if (e.productName == '门磁') {
                pic = 'iconfont menci'
            } else if (e.productName == '烟感探测报警器') {
                pic = 'iconfont yangan'
            } else if (e.productName == '红外探测器') {
                pic = 'iconfont rentihongwai'
            } else if (e.productName == '智能燃气报警器') {
                pic = 'iconfont reshuiqi'
            }
            return pic
        },
        //获取平面图设备标点
        async getGetMark() {
            const res = await reqGetMark(this.page, this.limit, {
                floorId: this.floorInfo.id,
                isMark: this.isMark,
                productId: this.productId
            })
            this.markId = ''
            this.total = res.data.row.count || 0
            this.markVOList = res.data.row.markVOList || []; //平面图点位
            this.markList = res.data.row.markVOList || [] //设备列表
            if (this.markVOList.length == 0) return;
            this.markVOList = this.markVOList.filter((item) => item.mark != "");
            this.markVOList.forEach((item) => {
                item.left = item.mark.slice(0, item.mark.indexOf(","));
                item.top = item.mark.slice(item.mark.indexOf(",") + 1);
            });
        },
        // 下拉请求列表
        enterpriseChange(val) {
            if (val) {
                this.getProductList();
            }
        },
        //   获取产品列表
        async getProductList() {
            const res = await reqProductList();
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.productList = res.data.rows;
        },
        // getimg(productName) {
        //     let pic = ''
        //     this.productList.forEach(item => {
        //         if (item.name == productName) {
        //             pic = item.pic
        //         }
        //     })
        //     return pic
        // },

        // 标记点图片
        getimg(e) {
            // console.log(e);
            let pic = 'iconfont shebeiguanli2'
            if (e.productName == '门磁') {
                pic = 'iconfont menci'
            } else if (e.productName == '烟感探测报警器') {
                pic = 'iconfont yangan'
            } else if (e.productName == '红外探测器') {
                pic = 'iconfont rentihongwai'
            } else if (e.productName == '智能燃气报警器') {
                pic = 'iconfont reshuiqi'
            }
            return pic
        },

        // 点击关闭弹框
        closeDialog() {
            // this.$parent.getImagePage()
            this.dialogVisible = false;
            this.markList = [];
            this.markId = '';
            this.flag = false;
            this.productId = ''
            this.isMark = ''
            this.scale = 1 // 初始缩放比例为1
            this.scaleStep = 0.1 // 每次滚动缩放的步长
            this.x = 0 // div的初始x坐标
            this.y = 0 // div的初始y坐标
            this.dragging = false // 是否正在拖动
            this.startX = 0 // 鼠标按下时的x坐标
            this.startY = 0 // 鼠标按下时的y坐标
        },
        // 上传文件之前的钩子
        beforeAvatarUpload(file) {
            let isJPG = true;
            let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
            if (file.type !== "image/png" && file.type !== "image/jpeg") {
                this.$modal.notifyWarning("图片只支持 jpg/png 格式");
                isJPG = false;
                return isJPG;
            } else if (!isLt) {
                this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
                isJPG = false;
            }
            return isJPG;
        },
        // 上传成功
        async handleSuccessFunction(response, file, fileList) {
            // console.log(file);
            this.floorInfo.image = file.response.data.url;
            const res = await reqImageBatchUpdate({
                idList: [this.floorInfo.id],
                image: this.floorInfo.image,
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.onrecover() //初始状态
            this.$modal.notifySuccess("图片上传成功");
        },
    },
};